﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace AudioCore.Common
{
    public class Utility
    {
        public static string GetRandomPassword(int length)
        {
            //char[] chars = "$%#@!*abcdefghijklmnopqrstuvwxyz1234567890?;:ABCDEFGHIJKLMNOPQRSTUVWXYZ^&".ToCharArray();
            char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890".ToCharArray();
            string password = string.Empty;
            Random random = new Random();

            for (int i = 0; i < length; i++)
            {
                int x = random.Next(1, chars.Length);
                //Don't Allow Repetation of Characters
                if (!password.Contains(chars.GetValue(x).ToString()))
                    password += chars.GetValue(x);
                else
                    i--;
            }
            return password;
        }
        /// <summary>
        /// Generate a random string by length
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GenRandomString(int length)
        {
            string ret = string.Empty;
            int r;
            Random rand = new Random(DateTime.Now.Millisecond);

            for (int i = 0; i < length; i++)
            {
                r = rand.Next((int)'0', (int)'z');
                while ((!(r >= (int)'0' && r <= (int)'9') &&
                        !(r >= (int)'A' && r <= (int)'Z') &&
                        !(r >= (int)'a' && r <= (int)'z')) ||
                        ret.Contains((char)r))
                {
                    r = rand.Next((int)'0', (int)'z');
                }
                ret += ((char)r).ToString();
            }

            return ret;
        }

        public static string EncodePassword(string originalPassword)
        {
            string key = GetRandomPassword(32);
            ////Declarations
            //Byte[] originalBytes;
            //Byte[] encodedBytes;
            //MD5 md5;

            ////Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            //md5 = new MD5CryptoServiceProvider();
            //originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword + key);
            //encodedBytes = md5.ComputeHash(originalBytes);

            ////Convert encoded bytes back to a 'readable' string
            //string pass = BitConverter.ToString(encodedBytes) + ":" + key;
            //pass = pass.Replace("-","");
            //return pass;
            return EncodePassword(originalPassword, key);
        }
        public static string EncodePassword(string originalPassword, string key)
        {
            //Declarations
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;

            //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword + key);
            encodedBytes = md5.ComputeHash(originalBytes);

            //Convert encoded bytes back to a 'readable' string
            string pass = BitConverter.ToString(encodedBytes) + ":" + key;
            pass = pass.Replace("-", "");
            return pass;
        }

        /// <summary>
        /// Validating the entered password from UI and password in the database
        /// </summary>
        /// <param name="loginPassword">Entered password</param>
        /// <param name="databasePassword">Password in the database</param>
        /// <returns></returns>
        public static bool ValidatePassword(string loginPassword, string databasePassword)
        {
            if (string.IsNullOrEmpty(loginPassword) || string.IsNullOrEmpty(databasePassword))
            {
                return false;
            }

            string encodedKey = databasePassword.Substring(databasePassword.LastIndexOf(':') + 1);

            if (Utility.EncodePassword(loginPassword, encodedKey).Equals(databasePassword))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Sample for test
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public static bool IsPhoneNumber(string phoneNumber)
        {
            if (string.IsNullOrEmpty(phoneNumber)) return false;

            Regex rgPhone = new Regex(@"(\+?84|0)\d{9,10}$");
            return rgPhone.IsMatch(phoneNumber);
            //string f;
            //int phoneNum;

            //if (phoneNumber.StartsWith("+"))
            //{
            //    f = phoneNumber.Substring(1);
            //}
            //else
            //{
            //    f = phoneNumber;
            //}
            //if (f.Length < 10 || 
            //    !int.TryParse(f, out phoneNum))
            //    return false;

            //return true;
        }

        public static string NormalizePhoneNumber(string phoneNumber)
        {
            const string countryCode = "84";
            const string plus = "+";
            const string zero = "0";
            string numberID = string.Empty;
            string result = string.Empty;

            // loai bo "0" va them "84" vao dau so phone number
            if (phoneNumber.StartsWith(zero))
            {
                phoneNumber = phoneNumber.Substring(zero.Length);
                phoneNumber = countryCode + phoneNumber;
            }

            // loai bo "+" ra khoi phone number
            if (phoneNumber.StartsWith(plus))
            {
                phoneNumber = phoneNumber.Substring(plus.Length);
            }

            return phoneNumber;
        }
        /// <summary>
        /// Normalize a string: 
        ///     + Trim begin, end space character
        ///     + remove all double space
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string NormalizeString(string str)
        {
            string result = str.Trim();
            result = result.Replace("  ", " ");

            return result;
        }
        public static string OptimizePhoneNumber(string phoneNumber)
        {
            const string countryCode = "84";
            const string plus = "+";
            const string zero = "0";
            string numberID = string.Empty;
            string result = string.Empty;
            string temp = phoneNumber;
            // Loai bo "+" ra khoi  dau so phone number
            if (phoneNumber.StartsWith(plus))
            {
                phoneNumber = phoneNumber.Substring(zero.Length);
            }

            // loai bo "84" ra khoi dau so phone number
            if (phoneNumber.StartsWith(countryCode))
            {
                phoneNumber = phoneNumber.Substring(countryCode.Length);
            }

            // them "0" vao dau so phone number
            if (temp.StartsWith(countryCode))
            {
                phoneNumber = zero + phoneNumber;
            }

            return phoneNumber;
        }

        /// <summary>
        /// Conver danh sach so sang 1 string dang: x, y, z
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ConvertListToString(List<int> list)
        {
            string result = string.Empty;
            if (list != null && list.Count > 0)
            {
                foreach (int num in list)
                {
                    result += num.ToString() + ", ";
                }
                if (result.EndsWith(", "))
                {
                    result = result.Remove(result.Length - 2);
                }
            }

            return result;
        }

        public static string GetFileExtension(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return string.Empty;
            }
            int index = fileName.LastIndexOf(".");
            if (index == -1)
            {
                return string.Empty;
            }
            else
            {
                return fileName.Substring(index);
            }
        }

        public static string GetFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return string.Empty;
            }
            int index = fileName.LastIndexOf("\\");
            if (index == -1)
            {
                return string.Empty;
            }
            else
            {
                return fileName.Substring(index + 1);
            }
        }
    }
}
